package top.lvkun.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.lvkun.basic.utils.AjaxResult;
import top.lvkun.basic.utils.RedisUtils;
import top.lvkun.user.domain.Shopcart;
import top.lvkun.user.domain.User;
import top.lvkun.user.service.IShopcartService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/shopcart")
public class ShopcartController {

    @Autowired
    private IShopcartService shopcartService;


    /**
     * 商品详情页添加到购物车
     * @param shopcart
     * @param request
     * @return
     */
    @PutMapping
    public AjaxResult addShopcart(@RequestBody Shopcart shopcart, HttpServletRequest request){
        try {
            User user = RedisUtils.INSTANCE.getUser(request, User.class);
            shopcart.setUser_id(user.getId());
            shopcartService.add(shopcart);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务繁忙！"+e.getMessage());
        }
    }

    /**
     * 获取当前用户的购物车信息
     * @param request
     * @return
     */
    @GetMapping
    public List<Shopcart> getShopcarts(HttpServletRequest request){
        try {
            //获取当前用户的购物车信息
            User user = RedisUtils.INSTANCE.getUser(request, User.class);
            return shopcartService.getShopcarts(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
